/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-29 10:57:05
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-09-24 17:37:34
 * @FilePath: /vue3-admin/src/service/biz/useMenu.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import {
    readMenuTree,
    MenuParam,
    readMenuDetail,
    createOrUpdateMenu,
    deleteMenu
} from '@/api/menu';
import { ref } from 'vue';
import type { MenuTreeItem, MenuDetial } from '@/typings/api/menu';
import { useEnum } from '@/service/useEnum';

export { MenuParam };

export const useMenu = () => {
    const tree = ref<MenuTreeItem[]>([]);
    const loading = ref(false);
    const { getMenuTreeTypes } = useEnum();
    const { update: menuTreeTypesUpdate } = getMenuTreeTypes();

    const getTree = () => {
        if (loading.value) return;
        loading.value = true;
        return readMenuTree()
            .then((res) => {
                tree.value = res.data;
                return res;
            })
            .finally(() => {
                loading.value = false;
            });
    };

    const detail = ref<MenuDetial>();
    const detailLoading = ref(false);

    const getDetail = (id: number) => {
        if (detailLoading.value) return;
        detailLoading.value = true;
        return readMenuDetail(id)
            .then((res) => {
                detail.value = res.data;
                return res;
            })
            .finally(() => {
                detailLoading.value = false;
            });
    };

    const updateLoading = ref(false);
    const updateMenu = (param: MenuParam) => {
        if (updateLoading.value) return;
        updateLoading.value = true;
        return createOrUpdateMenu(param)
            .then(() => {
                menuTreeTypesUpdate();
            })
            .finally(() => {
                updateLoading.value = false;
            });
    };

    const removeLoading = ref(false);
    const removeMenu = (id: number) => {
        if (removeLoading.value) return;
        removeLoading.value = true;
        return deleteMenu(id)
            .then((res) => {
                menuTreeTypesUpdate();
                return res;
            })
            .finally(() => {
                removeLoading.value = false;
            });
    };

    return {
        loading,
        getTree,
        tree,
        detail,
        detailLoading,
        getDetail,
        updateMenu,
        updateLoading,
        removeLoading,
        removeMenu
    };
};
